package com.easymin.weixin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.easymin.weixin.service.WeixinQrCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhyu
 * @date 2019-07-13 17:16:37
 */
@Service
public class WeixinQrCodeServiceImpl implements WeixinQrCodeService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${weixin.appId}")
    private String appId;
    @Value("${weixin.secret}")
    private String secret;

    public static final String BIND_TYPE = "bind";

    public static final String SEPARATE = "and";
    /***
     * 获取微信代参关注二维码第一步 获取access_token
     */
    public static final String WEIXIN_GET_ACCESS_TOKEN_URL =
            "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={1}&secret={2}";

    /***
     * 获取微信代参关注二维码第二部 获取ticket 或者 二维码的url
     */
    public static final String WEIXIN_GET_URL_AND_TICKET = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={1}";

    /***
     * 获取微信代参二维码第三部  可选! 因为第二步已得到url
     */
    public static final String WEIXIN_GET_QRCODE = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={1}";
    @Override
    public String[] getWeixinQrCodeService(String driverId, String name) {
        String accessToken = getAccessToken();
        String url = null;
        if(null != accessToken){
            String[] urlAndTicket = getUrlAndTicket(accessToken, driverId, name);
            if(null != urlAndTicket && urlAndTicket.length > 1) {
                return urlAndTicket;
            }
        }
        return null;
    }

    public static final String FINAL_QR_STR = "QR_LIMIT_STR_SCENE";

    public static final String QR_STR = "QR_STR_SCENE";
    public static final int QR_STR_CODE = 604800;
    /***
     * 获取微信代参关注二维码第二部 获取ticket 或者 二维码的url
     * @param accessToken
     * @param driverId
     * @return index 0 = ticket; index 1 = url
     */
    public String[] getUrlAndTicket(String accessToken, String driverId, String name) {
        Map<String,String> aa=new HashMap<>();//封装微信参数
        aa.put("access_token",accessToken);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        JSONObject jsonObj = new JSONObject();
//        jsonObj.put("accessToken",accessToken);
//        jsonObj.put("expire_seconds", QR_STR_CODE);
        jsonObj.put("action_name", FINAL_QR_STR);
        JSONObject str = new JSONObject();
        str.put("scene_str", BIND_TYPE + SEPARATE + driverId + SEPARATE + name);
        JSONObject info = new JSONObject();
        info.put("scene", str);
        jsonObj.put("action_info", info);
        HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);
        JSONObject re = restTemplate.postForEntity(WEIXIN_GET_URL_AND_TICKET, formEntity,
                JSONObject.class, accessToken).getBody();
        if(null != re){
            String ticket = re.getString("ticket");
            String url = re.getString("url");
            String[] res = new String[3];
            res[0] = ticket;
            res[1] = url;
            res[2] = accessToken;
            return res;
        }
        return null;
    }

    /**
     * 获取微信代参关注二维码第一步 获取access_token
     * @return
     */
    public String getAccessToken() {
        JSONObject re = restTemplate.getForObject(WEIXIN_GET_ACCESS_TOKEN_URL, JSONObject.class, appId, secret);
        if(7200 == re.getInteger("expires_in")){
            return re.getString("access_token");
        }else {
            return null;
        }
    }
    static class Result {
        private Integer code;
        private String msg;
        private Object data;
    }
}
